﻿//-----------------------------------------------------------------------
// <copyright file="ImageHelper.cs" company="Steve Syrell">
//     Copyright 2012 Steve Syrell
// </copyright>
//-----------------------------------------------------------------------

namespace SteveSyrell.Tools.Phone.Imaging
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.IO.IsolatedStorage;
    using System.Threading;
    using System.Windows.Media.Imaging;

    /// <summary>
    /// Helper methods dealing with images.
    /// </summary>
    public static class ImageHelper
    {
        /// <summary>
        /// The dictionary of file paths.
        /// </summary>
        private static Dictionary<Uri, string> filePaths = new Dictionary<Uri, string>();

        /// <summary>
        /// Saves the specified image to disk.
        /// </summary>
        /// <param name="imageUri">The URI of the image to save.</param>
        /// <param name="filePath">The full path of the file to save the image to.</param>
        /// <param name="overwriteExisting">A value indicating whether to overwrite the file if it exists.</param>
        public static void SaveImageToDisk(Uri imageUri, string filePath, bool overwriteExisting)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string fileDirectory = Path.GetDirectoryName(filePath);

                if (!store.DirectoryExists(fileDirectory))
                {
                    store.CreateDirectory(fileDirectory);
                }

                // Check to see if the file exists
                bool fileExists = store.FileExists(filePath);

                if (!fileExists || (fileExists && overwriteExisting))
                {
                    ImageHelper.filePaths[imageUri] = filePath;
                    BitmapImage image = new BitmapImage();
                    image.CreateOptions = BitmapCreateOptions.None;
                    image.UriSource = imageUri;
                    image.ImageOpened += ImageHelper.OnImageOpened;
                }
            }
        }

        /// <summary>
        /// Executes when an image is successfully downloaded.
        /// </summary>
        /// <param name="sender">The object calling this method.</param>
        /// <param name="e">Event arguments.</param>
        private static void OnImageOpened(object sender, System.Windows.RoutedEventArgs e)
        {
            BitmapImage downloadedImage = sender as BitmapImage;

            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(ImageHelper.filePaths[downloadedImage.UriSource], FileMode.Create, store))
                {
                    WriteableBitmap bitmap = new WriteableBitmap(downloadedImage);
                    bitmap.SaveJpeg(fileStream, downloadedImage.PixelWidth, downloadedImage.PixelHeight, 0, 100);
                    fileStream.Flush();
                    fileStream.Close();
                }
            }
        }
    }
}
